import React, { Component } from 'react';
import RouterContext from '../RouterContext';

// 他的父级有三种情况：BrowserRouter，HashRouter，MemoryRouter。我们在这个组件里面消除差异性
export default class Router extends Component {
  // 默认值，处理没有path的情况
  static computeRootMatch(pathname) {
    return { path: '/', url: '/', params: {}, isExact: pathname === '/' };
  }
  constructor(props) {
    super(props);
    this.state = {
      location: props.history.location,
    };

    // 监听 location 的变化  重新渲染子组件
    this.unListen = props.history.listen(({ location }) => {
      this.setState({ location });
    });
  }

  componentWillUnmount() {
    this.unListen && this.unListen();
  }

  render() {
    const { children, history } = this.props;
    return (
      <RouterContext.Provider
        value={{
          history,
          location: this.state.location,
          match: Router.computeRootMatch(this.state.location.pathname),
        }}
      >
        {children}
      </RouterContext.Provider>
    );
  }
}
